// ... existing code ...

// 处理聊天消息
socket.on('chat message', async (msg) => {
  console.log('收到消息:', msg);
  
  try {
    // 判断是私聊还是群聊
    if (msg.isRoom && msg.roomId) {
      // 群聊消息，广播给所有在线的群成员
      const chatRoom = await ChatRoom.findOne({ where: { roomId: msg.roomId } });
      if (chatRoom) {
        const members = JSON.parse(chatRoom.members || '[]');
        
        // 更新最后聊天时间
        await ChatHistory.update(
          { lastTime: new Date() },
          { where: { roomId: msg.roomId } }
        );
        
        // 广播消息给所有在线的群成员
        members.forEach(member => {
          const memberSocket = userSockets[member];
          if (memberSocket && member !== msg.username) {
            memberSocket.emit('chat message', msg);
          }
        });
      }
    } else {
      // 私聊消息，发送给特定用户
      const targetSocket = userSockets[msg.receive];
      
      // 更新最后聊天时间
      await ChatHistory.update(
        { lastTime: new Date() },
        { 
          where: { 
            $or: [
              { username: msg.username, receive: msg.receive },
              { username: msg.receive, receive: msg.username }
            ]
          }
        }
      );
      
      if (targetSocket) {
        targetSocket.emit('chat message', msg);
      }
    }
  } catch (error) {
    console.error('处理消息异常:', error);
  }
});